import socketserver
import random
import time


class TcpServer(socketserver.BaseRequestHandler):
    # 首先执行
    def setup(self):
        pass

    # 然后执行
    def handle(self):
        conn = self.request

        msg = "准备连接..."
        conn.send(msg.encode())

        while True:
            data = conn.recv(1024)
            print(data.decode())

            # 如果接收的是exit，则退出
            if data == b'exit':
                break

            # 如果接收的是其他消息，则先发送第一个原数据
            conn.send(data)
            print('send first msg success')
            # 睡一小会，否则两个消息会一同接收，导致第二个recv阻塞
            time.sleep(1)
            # 发送第二个随机数
            conn.send(str(random.randint(1, 100)).encode())
            print('send second msg success')
        conn.close()

    # 最后执行
    def finish(self):
        pass


if __name__ == "__main__":
    server = socketserver.ThreadingTCPServer(("127.0.0.1", 8881), TcpServer)
    server.serve_forever()


# cpu-90%
# send first msg success
# send second msg success
# memory-8G
# send first msg success
# send second msg success
# harddisk-1000G
# send first msg success
# send second msg success
# localhost-127.0.0.1
# send first msg success
# send second msg success
# exit